﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;

namespace FileTransferSystem.Services
{
    /// <summary>
    /// 端口扫描器，用于查找可用端口
    /// </summary>
    public static class PortScanner
    {
        /// <summary>
        /// 查找可用端口
        /// </summary>
        public static void FindAvailablePorts()
        {
            var availablePorts = FindAvailablePortsList();

            Console.WriteLine($"找到 {availablePorts.Count} 个可用端口:");
            foreach (var port in availablePorts.Take(10)) // 只显示前10个
            {
                Console.WriteLine($"端口: {port}");
            }

            if (availablePorts.Count > 10)
            {
                Console.WriteLine("... 更多端口未显示");
            }
        }

        /// <summary>
        /// 查找可用端口列表
        /// </summary>
        public static List<int> FindAvailablePortsList()
        {
            var availablePorts = new List<int>();
            var startPort = 8000;
            var endPort = 9000;

            for (int port = startPort; port <= endPort; port++)
            {
                if (IsPortAvailable(port))
                {
                    availablePorts.Add(port);
                }
            }

            return availablePorts;
        }

        /// <summary>
        /// 检查端口是否可用（可用于接收文件）
        /// </summary>
        public static bool IsPortAvailable(int port)
        {
            try
            {
                var listener = new TcpListener(System.Net.IPAddress.Loopback, port);
                listener.Start();
                listener.Stop();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}